package com.cracker.websocket.server.event.listener.sessionOnline;

import com.cracker.websocket.server.entity.UserEntity;
import com.cracker.websocket.server.event.SessionOnlineEvent;
import com.cracker.websocket.server.service.SessionService;
import com.cracker.websocket.server.service.StatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;

/**
 * 在线统计
 */
@Component
@Slf4j
public class OnlineStat implements ApplicationListener<SessionOnlineEvent> {
    @Autowired
    private SessionService sessionService;
    @Autowired
    private StatService statService;

    @Override
    public void onApplicationEvent(SessionOnlineEvent sessionOnlineEvent) {
        Session session = sessionOnlineEvent.getSession();
        UserEntity userEntity = (UserEntity) session.getUserProperties().get("user");
        sessionService.sessionOnline(session, userEntity);
        statService.incOnlineCount();
        log.warn("用户id:{} 上线,当前在线人数:{}", userEntity.getId(), statService.getOnlineCount());
    }
}
